package com.zlx.sharelive.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Patterns;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.zhouwei.library.CustomPopWindow;
import com.loonggg.rvbanner.lib.RecyclerViewBanner;
import com.lzj.pass.dialog.PayPassDialog;
import com.lzj.pass.dialog.PayPassView;
import com.paradoxie.autoscrolltextview.VerticalTextview;
import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.BaseInfoBean;
import com.zlx.module_base.base_api.res_data.GuessLikeVideoBody;
import com.zlx.module_base.base_api.res_data.HomeBannerBean;
import com.zlx.module_base.base_api.res_data.HomeLinkBean;
import com.zlx.module_base.base_api.res_data.HomeRollAnnouncementBean;
import com.zlx.module_base.base_api.res_data.PurchaseVideoBean;
import com.zlx.module_base.base_api.res_data.QueryByBean;
import com.zlx.module_base.base_api.res_data.VideoBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_fg.BaseFg;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.activity.AuctionAc;
import com.zlx.sharelive.activity.FrequencyListAc;
import com.zlx.sharelive.activity.HomeLinkAc;
import com.zlx.sharelive.activity.HomeSearchAc;
import com.zlx.sharelive.activity.ImageTextAc;
import com.zlx.sharelive.activity.LoginAc;
import com.zlx.sharelive.activity.MemberAc;
import com.zlx.sharelive.activity.RankingAc;
import com.zlx.sharelive.activity.RechargeAc;
import com.zlx.sharelive.activity.RecommendListAc;
import com.zlx.sharelive.activity.ReleaseVideoAc;
import com.zlx.sharelive.activity.ShortVideoAc;
import com.zlx.sharelive.activity.TextAc;
import com.zlx.sharelive.activity.VideoDetailsAc;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.NullTokenUtils;
import com.zlx.sharelive.utils.StringUt;

import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页
 */
public class HomeFg extends BaseFg {

    @BindView(R.id.rcBanner)
    RecyclerViewBanner rcBanner;
    @BindView(R.id.rv_recommend)
    RecyclerView rv_recommend;
    @BindView(R.id.rv_classification)
    RecyclerView rv_classification;
    @BindView(R.id.iv_home_dialog)
    ImageView iv_home_dialog;
    @BindView(R.id.tv_newest)
    TextView tv_newest;
    @BindView(R.id.tv_attention)
    TextView tv_attention;
    @BindView(R.id.tv_choice)
    TextView tv_choice;
    @BindView(R.id.tv_feezone)
    TextView tv_feezone;
    @BindView(R.id.iv_newest)
    ImageView iv_newest;
    @BindView(R.id.iv_attention)
    ImageView iv_attention;
    @BindView(R.id.iv_choice)
    ImageView iv_choice;
    @BindView(R.id.iv_feezone)
    ImageView iv_feezone;
    @BindView(R.id.sw_layout)
    SwipeRefreshLayout sw_layout;
    @BindView(R.id.tv_gonggao)
    VerticalTextview tv_gonggao;

    private BaseInfoBean mBaseInfoBean;
    private String over;
    private int videoCount;
    private int page = 1;
    private int page2 = 1;
    private String type1 = "1";//长视频 2短视频
    private String state = "1";//1最新 2收费
    private List<TextView> textViewList;
    private List<ImageView> imageViewList;
    private List<HomeBannerBean.InfoDTO> banner = new ArrayList<>();
    private List<VideoBean.InfoDTO.RecordsDTO> recommend = new ArrayList<>();
    private List<VideoBean.InfoDTO.RecordsDTO> classification = new ArrayList<>();
    private CommonRecyclerViewAdapter<VideoBean.InfoDTO.RecordsDTO> recommendAdapter;
    private CommonRecyclerViewAdapter<VideoBean.InfoDTO.RecordsDTO> classificationAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fg_home;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    recommendAdapter.notifyItemChanged(msg.arg1);
                    break;
                case 2:
                    classificationAdapter.notifyItemChanged(msg.arg1);
                    break;
            }
        }
    };

    @Override
    protected void initViews() {
        super.initViews();
        //lottery
        SPUtil.put(getContext(), Constants.SP_LOTTERY, "");

        initTextView();
        initRecommend();
        initClassification();

        //网络请求
        getBaseInfo();
        getHomeRollAnnouncement();
        if (StringUt.isEmpty((String) SPUtil.get(getContext(), Constants.SP_LOTTERY, ""))) {
            getHomeBannerList2();
        }

        sw_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                setTextCheck(0);
                page = 1;
                page2 = 1;
                type1 = "1";
                state = "1";
                getHomeToday(page);
                getHomeBannerList();
                getVideoList(page2, type1, state);
                queryById();
            }
        });
    }

    /**
     * 用户基本信息
     */
    private void getBaseInfo() {
        ApiUtil.getUserApi().getBaseInfo(SPUtil.getToken(getContext())).
                observe(getViewLifecycleOwner(), new BaseObserver<>(
                        new BaseObserverCallBack<ApiResponse<BaseInfoBean>>() {
                            @Override
                            public void onSuccess(ApiResponse<BaseInfoBean> data) {
                                if (null != data) {
                                    if (null != data.getData()) {
                                        if (data.getData().getCode() == 0) {
                                            if (null != data.getData().getInfo()) {
                                                mBaseInfoBean = data.getData();
                                            }
                                        } else {
                                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();

                            }
                        }));
    }


    /**
     * 首页滚动公告
     */
    private void getHomeRollAnnouncement() {
        ApiUtil.getHomeApi().getHomeRollAnnouncement().observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<HomeRollAnnouncementBean>>() {
            @Override
            public void onSuccess(ApiResponse<HomeRollAnnouncementBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (tv_gonggao.getChildCount() < 2) {
                                ArrayList<String> titleList = new ArrayList<>();
                                for (int i = 0; i < data.getData().getInfo().size(); i++) {
                                    if (data.getData().getInfo().get(i).getType().equals("0")) {
                                        titleList.add(data.getData().getInfo().get(i).getNickName() + " 发布新的短视频");
                                    } else if (data.getData().getInfo().get(i).getType().equals("1")) {
                                        titleList.add(data.getData().getInfo().get(i).getNickName() + " 发布新的长视频");
                                    } else if (data.getData().getInfo().get(i).getType().equals("2")) {
                                        titleList.add(data.getData().getInfo().get(i).getNickName() + " 发布新的动态");
                                    } else if (data.getData().getInfo().get(i).getType().equals("3")) {
                                        titleList.add(data.getData().getInfo().get(i).getNickName() + " 发布新的文章");
                                    }
                                }
                                tv_gonggao.setTextList(titleList);//加入显示内容,集合类型
                                tv_gonggao.setTextStillTime(3000);//设置停留时长间隔
                                tv_gonggao.setAnimTime(300);//设置进入和退出的时间间隔
                                //对单条文字的点击监听
                                tv_gonggao.setOnItemClickListener(new VerticalTextview.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(int position) {
                                        // TO DO
                                    }
                                });
                                tv_gonggao.startAutoScroll();
                            }
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }
        }));
    }

    @Override
    public void onStart() {
        super.onStart();

        getHomeToday(page);
        getHomeBannerList();
        getVideoList(page2, type1, state);
        queryById();
    }

    private void getHomeBannerList2() {
        ApiUtil.getHomeApi().getHomeBannerList("3").observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<HomeBannerBean>>() {
            @Override
            public void onSuccess(ApiResponse<HomeBannerBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    dialogLottery(data.getData().getInfo().get(0).getImg()
                                            , data.getData().getInfo().get(0).getLink()
                                            , data.getData().getInfo().get(0).getTitle());
                                }
                            }
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                sw_layout.setRefreshing(false);
            }
        }));

    }

    private void getHomeLink(int type) {
        ApiUtil.getHomeApi().getHomeLink().observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<HomeLinkBean>>() {
            @Override
            public void onSuccess(ApiResponse<HomeLinkBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    if (type == 1) {
                                        startActivity(new Intent(getContext(),
                                                HomeLinkAc.class)
                                                .putExtra("url", data.getData().getInfo().get(0).getCjLink()));
                                    } else {
                                        startActivity(new Intent(getContext(),
                                                HomeLinkAc.class)
                                                .putExtra("url", data.getData().getInfo().get(0).getDiscountsLink()));
                                    }
                                }
                            }
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }
        }));
    }

    private void dialogLottery(String img, String link, String title) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getContext(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getContext(), R.layout.dialog_lottery, null);
        dialog.setContentView(view);

        ImageView iv_image = view.findViewById(R.id.iv_image);
        GlideImgManager.glideLoader(getContext(),
                img, iv_image, 1);

        TextView tv_title = view.findViewById(R.id.tv_title);
        if (StringUt.isEmpty(title)) {
            tv_title.setVisibility(View.GONE);
        } else {
            tv_title.setVisibility(View.VISIBLE);
        }
        tv_title.setText(title);

        iv_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                抽奖页面
                dialog.dismiss();
                startActivity(new Intent(getContext(),
                        HomeLinkAc.class)
                        .putExtra("url", link));
            }
        });

        ImageView iv_dism_dialog = view.findViewById(R.id.iv_dism_dialog);
        iv_dism_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                SPUtil.put(getContext(), Constants.SP_LOTTERY, "1");
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 根据用户id查询个人信息
     */
    private void queryById() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(getContext()),(String) SPUtil.get(getContext(), Constants.SP_ID, ""))
                .observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
                    @Override
                    public void onSuccess(ApiResponse<QueryByBean> data) {
                        if (null != data) {
                            if (null != data.getData()) {
                                if (data.getData().getCode() == 0) {
                                    if (null != data.getData().getInfo()) {
                                        if (data.getData().getInfo().size() > 0) {
                                            if (null != data.getData().getInfo().get(0).getResult()) {
                                                if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getVideoCount())) {
                                                    videoCount = Integer.valueOf(data.getData().getInfo().get(0).getResult().getVideoCount());
                                                    if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getMoney())) {
                                                        over = data.getData().getInfo().get(0).getResult().getMoney();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                                }
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                }));
    }

    /**
     * 视频列表
     * p
     * [string]	是	页数
     * type1
     * [string]	是	1 长视频 2 短视频
     * state
     * [string]	是	视频列表种类 1 最新 2 收费
     * id
     * [string]	是	频道id (频道筛选时使用)
     */
    private void getVideoList(int page, String type, String state) {
        ApiUtil.getHomeApi().getVideoList(SPUtil.getToken(getContext()),
                String.valueOf(page),
                type, state, "", "", "",
                (String) SPUtil.get(getContext(), Constants.SP_ID, "")
                , "", "", "1"
        ).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<VideoBean>>() {
            @Override
            public void onSuccess(ApiResponse<VideoBean> data) {
                sw_layout.setRefreshing(false);
                classification.clear();
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    if (null != data.getData().getInfo().get(0).getRecords()) {
                                        for (int i = 0; i < data.getData().getInfo().get(0).getRecords().size(); i++) {
                                            if (data.getData().getInfo().get(0).getRecords().get(i).getCheckStatus().equals("1")) {
                                                classification.add(data.getData().getInfo().get(0).getRecords().get(i));
                                            }
                                        }
                                    }
                                }
                            }
                            classificationAdapter.notifyDataSetChanged();

                            for (int i = 0; i < classification.size(); i++) {
                                final String video = classification.get(i).getVideo();
                                final int position = i;
                                new Thread() {
                                    @Override
                                    public void run() {
                                        super.run();
                                        if (!StringUt.isEmpty(video)) {
                                            if (isValid(video) == true) {
                                                if (!StringUt.isEmpty(getPlayTime(video))) {
                                                    String time = getFormatedDateTime("mm:ss", Long.valueOf(getPlayTime(video)));
                                                    classification.get(position).setPeriod(time);
                                                    Message msg = new Message();
                                                    msg.what = 2;
                                                    msg.arg1 = position;
                                                    handler.sendMessage(msg);
                                                }
                                            }
                                        }
                                    }
                                }.start();
                            }
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }

            }

            @Override
            public void onFinish() {
                super.onFinish();
                sw_layout.setRefreshing(false);
            }
        }));
    }

    /**
     * 首页轮播图
     */
    private void getHomeBannerList() {
        ApiUtil.getHomeApi().getHomeBannerList("1").observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<HomeBannerBean>>() {
            @Override
            public void onSuccess(ApiResponse<HomeBannerBean> data) {
                sw_layout.setRefreshing(false);
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            banner.clear();
                            banner.addAll(data.getData().getInfo());
                            initBanner(banner);
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                sw_layout.setRefreshing(false);
            }
        }));
    }

    /**
     * 首页今日推荐
     */
    private void getHomeToday(int page) {
        ApiUtil.getVideoApi().getHomeTodayRecommend(SPUtil.getToken(getContext()), type1, String.valueOf(page),
                "1").observe(
                getViewLifecycleOwner(), new BaseObserver<>(
                        new BaseObserverCallBack<ApiResponse<VideoBean>>() {
                            @Override
                            public void onSuccess(ApiResponse<VideoBean> data) {
                                sw_layout.setRefreshing(false);
                                recommend.clear();
                                if (null != data) {
                                    if (null != data.getData()) {
                                        if (data.getData().getCode() == 0) {
                                            if (null != data.getData().getInfo()) {
                                                if (data.getData().getInfo().size() > 0) {
                                                    if (null != data.getData().getInfo().get(0).getRecords()) {
                                                        for (int i = 0; i < data.getData().getInfo().get(0).getRecords().size(); i++) {
                                                            if (data.getData().getInfo().get(0).getRecords().get(i).getCheckStatus().equals("1")) {
                                                                recommend.add(data.getData().getInfo().get(0).getRecords().get(i));
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        } else {
                                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                                        }
                                    }
                                }
                                recommendAdapter.notifyDataSetChanged();

                                for (int i = 0; i < recommend.size(); i++) {
                                    final String video = recommend.get(i).getVideo();
                                    final int position = i;
                                    new Thread() {
                                        @Override
                                        public void run() {
                                            super.run();
                                            if (!StringUt.isEmpty(video)) {
                                                if (isValid(video) == true) {
                                                    if (!StringUt.isEmpty(getPlayTime(video))) {
                                                        String time = getFormatedDateTime("mm:ss", Long.valueOf(getPlayTime(video)));
                                                        recommend.get(position).setPeriod(time);
                                                        Message msg = new Message();
                                                        msg.what = 1;
                                                        msg.arg1 = position;
                                                        handler.sendMessage(msg);
                                                    }
                                                }
                                            }
                                        }
                                    }.start();
                                }
                            }

                            @Override
                            public void onFail(String msg) {
                                super.onFail(msg);
                                sw_layout.setRefreshing(false);
                            }
                        }));
    }

    /**
     * 初始化按钮
     */
    private void initTextView() {
        textViewList = new ArrayList<>();
        textViewList.clear();
        imageViewList = new ArrayList<>();
        imageViewList.clear();

        textViewList.add(tv_newest);
        textViewList.add(tv_attention);
        textViewList.add(tv_choice);
        textViewList.add(tv_feezone);
        imageViewList.add(iv_newest);
        imageViewList.add(iv_attention);
        imageViewList.add(iv_choice);
        imageViewList.add(iv_feezone);
    }


    /**
     * 初始化轮播图
     */
    private void initBanner(List<HomeBannerBean.InfoDTO> banner) {
        rcBanner.isShowIndicator(true);
        rcBanner.setRvBannerData(banner);
        rcBanner.setOnSwitchRvBannerListener(new RecyclerViewBanner.OnSwitchRvBannerListener() {
            @Override
            public void switchBanner(int i, AppCompatImageView appCompatImageView) {
                appCompatImageView.setScaleType(ImageView.ScaleType.FIT_XY);
                GlideImgManager.glideLoader(getContext(), banner.get(i).getImg(), appCompatImageView, 1);
            }
        });
        rcBanner.setOnRvBannerClickListener(new RecyclerViewBanner.OnRvBannerClickListener() {
            @Override
            public void onClick(int position) {
                startActivity(new Intent(getContext(),
                        HomeLinkAc.class)
                        .putExtra("url", banner.get(position).getLink()));
            }
        });
    }

    /**
     * 初始化今日推荐
     */
    private void initRecommend() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_recommend.setLayoutManager(layoutManager);

        recommendAdapter = new CommonRecyclerViewAdapter<VideoBean.InfoDTO.RecordsDTO>(getContext(), recommend) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, VideoBean.InfoDTO.RecordsDTO entity, int position) {

                GlideImgManager.glideLoader(getContext(), entity.getCover(), holder.getView(R.id.iv_recommend), 1);

                GlideImgManager.glideLoader(getContext(), entity.getAvatar(), holder.getView(R.id.iv_recommend_head), 0);

                holder.setText(R.id.tv_recommend_title, entity.getTitle());

                holder.setText(R.id.tv_recommend_nickname, entity.getNickname());

                holder.setText(R.id.tv_time, entity.getPeriod());

                if (entity.getIslike().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img_true);
                } else {
                    ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img_false);
                }

                if (entity.getIsVip().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_vip)).setVisibility(View.VISIBLE);
                } else {
                    ((ImageView) holder.getView(R.id.iv_vip)).setVisibility(View.GONE);
                }
                if (!StringUt.isEmpty(entity.getAuthentication())) {
                    if (entity.getAuthentication().equals("1")) {
                        ((ImageView) holder.getView(R.id.iv_authentication)).setVisibility(View.VISIBLE);
                    } else {
                        ((ImageView) holder.getView(R.id.iv_authentication)).setVisibility(View.GONE);
                    }
                }
                holder.setText(R.id.tv_pageViews, entity.getPageViews());
                holder.setText(R.id.tv_fabulous, entity.getLikeCount());
                holder.setText(R.id.tv_comment_count, entity.getCommentCount());
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_recommend;
            }
        };

        rv_recommend.setAdapter(recommendAdapter);

        recommendAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                //先判断是否登录
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    if (recommend.get(position).getIsMe().equals("1")) {
                        startActivity(new Intent(getContext(), VideoDetailsAc.class)
                                .putExtra("id", recommend.get(position).getId())
                                .putExtra("title", recommend.get(position).getTitle()));
                    } else {
                        if (recommend.get(position).getIsPaid().equals("1")) {
                            //免费还有次数
                            if (videoCount > 0) {
                                dialogFreePlay(recommend.get(position).getId()
                                        , recommend.get(position).getTitle());
                            } else {
                                //没有免费次数 弹出充值会员
                                dialogMember();
                            }
                        } else {
                            //收费
                            if (StringUt.isEmpty(recommend.get(position).getIsFlag())) {
                                //为空 未购买
                                dialogPay(
                                        recommend.get(position).getId(),
                                        recommend.get(position).getMoney());
                            } else {
                                if (recommend.get(position).getIsFlag().equals("0")) {
                                    //未购买 弹出购买窗口
                                    dialogPay(
                                            recommend.get(position).getId(),
                                            recommend.get(position).getMoney());
                                } else {//已购买
                                    startActivity(new Intent(getContext(), VideoDetailsAc.class)
                                            .putExtra("id", recommend.get(position).getId())
                                            .putExtra("title", recommend.get(position).getTitle()));
                                }
                            }
                        }
                    }
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
            }
        });
    }

    private void dialogMember() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getContext(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getContext(), R.layout.dialog_home_member, null);
        dialog.setContentView(view);

        TextView tv_video_count = view.findViewById(R.id.tv_video_count);
        tv_video_count.setText(videoCount + "");

        Button bt_member = view.findViewById(R.id.bt_member);

        bt_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), MemberAc.class)
                        .putExtra("data", mBaseInfoBean));
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 购买
     */
    private void dialogPay(String id, String money) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getContext(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getContext(), R.layout.dialog_play_video, null);
        dialog.setContentView(view);

        TextView tv_money = view.findViewById(R.id.tv_money);
        tv_money.setText("￥" + money);

        TextView tv_over = view.findViewById(R.id.tv_over);

        ImageView iv_close = view.findViewById(R.id.iv_close);

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        if (StringUt.isEmpty(over)) {
            tv_over.setText("￥0");
        } else {
            tv_over.setText("￥" + over);
        }

        TextView bt_play = view.findViewById(R.id.bt_play);

        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUt.isEmpty(money) && !StringUt.isEmpty(over)) {
                    if (Double.valueOf(over) > Double.valueOf(money)) {
                        //钱够支付
                        purchaseVideo(id, money);
                        dialog.dismiss();
                    } else {
                        Toast.makeText(getContext(), "余额不足", Toast.LENGTH_SHORT).show();
                    }
                } else if (StringUt.isEmpty(over)) {
                    Toast.makeText(getContext(), "余额不足", Toast.LENGTH_SHORT).show();
                }
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 余额购买视频
     *
     * @param id
     * @param money
     */
    private void purchaseVideo(String id, String money) {
        dialogPass(id, money);
    }

    /**
     * 支付密码
     */
    private void dialogPass(String id, String money) {
        PurchaseVideoBean purchaseVideoBean = new PurchaseVideoBean();
        purchaseVideoBean.setId(id);
        purchaseVideoBean.setMoney(money);

        final PayPassDialog dialog = new PayPassDialog(getContext());
        dialog.getPayViewPass()
                .setRandomNumber(true)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String passContent) {
                        //6位输入完成回调
                        Log.d("ret", "joker  输入的密码===" + passContent);
                        purchaseVideoBean.setPayPassWord(passContent);

                        ApiUtil.getVideoApi().purchaseVideo(SPUtil.getToken(getContext()),
                                purchaseVideoBean).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
                            @Override
                            public void onSuccess(ApiResponse<BaseBean> data) {
                                if (data.getData().getCode() == 0) {
                                    Toast.makeText(getContext(), "购买成功", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                    page = 1;
                                    page2 = 1;
                                    getHomeToday(page);
                                    getHomeBannerList();
                                    getVideoList(page2, type1, state);
                                    queryById();
                                } else {
                                    NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                                }
                            }
                        }));
                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭弹框
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();
                        //点击忘记密码回调
                    }
                });

    }

    /**
     * 弹出观看视频友情提示
     */
    private void dialogFreePlay(String id, String title) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getContext(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getContext(), R.layout.dialog_home_play, null);
        dialog.setContentView(view);

        TextView tv_video_count = view.findViewById(R.id.tv_video_count);
        tv_video_count.setText(videoCount + "");

        RelativeLayout ll_dialog_play = view.findViewById(R.id.ll_dialog_play);

        RelativeLayout rl_close = view.findViewById(R.id.rl_close);
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        ll_dialog_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), VideoDetailsAc.class)
                        .putExtra("id", id)
                        .putExtra("title", title));
                dialog.dismiss();
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 初始化分类
     */
    private void initClassification() {
        rv_classification.setLayoutManager(new GridLayoutManager(getContext(), 2));

        classificationAdapter = new CommonRecyclerViewAdapter<VideoBean.InfoDTO.RecordsDTO>(getContext(), classification) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, VideoBean.InfoDTO.RecordsDTO entity, int position) {

                GlideImgManager.glideLoader(getContext(), entity.getCover(), holder.getView(R.id.iv_recommend), 1);

                GlideImgManager.glideLoader(getContext(), entity.getAvatar(), holder.getView(R.id.iv_recommend_head), 0);

                holder.setText(R.id.tv_recommend_title, entity.getTitle());

                holder.setText(R.id.tv_recommend_nickname, entity.getNickname());

                if (entity.getIslike().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img_true);
                } else {
                    ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img_false);
                }

                holder.setText(R.id.tv_time, entity.getPeriod());

                if (!StringUt.isEmpty(entity.getIsVip())) {
                    if (entity.getIsVip().equals("1")) {
                        ((ImageView) holder.getView(R.id.iv_vip)).setVisibility(View.VISIBLE);
                    } else {
                        ((ImageView) holder.getView(R.id.iv_vip)).setVisibility(View.GONE);
                    }
                }
                if (!StringUt.isEmpty(entity.getAuthentication())) {
                    if (entity.getAuthentication().equals("1")) {
                        ((ImageView) holder.getView(R.id.iv_authentication)).setVisibility(View.VISIBLE);
                    } else {
                        ((ImageView) holder.getView(R.id.iv_authentication)).setVisibility(View.GONE);
                    }
                }
                holder.setText(R.id.tv_pageViews, entity.getPageViews());
                holder.setText(R.id.tv_fabulous, entity.getLikeCount());
                holder.setText(R.id.tv_commentCount, entity.getCommentCount());
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_classification;
            }
        };

        rv_classification.setAdapter(classificationAdapter);

        classificationAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    if (classification.get(position).getIsMe().equals("1")) {
                        //自己的
                        startActivity(new Intent(getContext(), VideoDetailsAc.class)
                                .putExtra("id", classification.get(position).getId())
                                .putExtra("title", classification.get(position).getTitle()));
                    } else {
                        if (classification.get(position).getIsPaid().equals("1")) {
                            //免费还有次数
                            if (videoCount > 0) {
                                dialogFreePlay(classification.get(position).getId()
                                        , classification.get(position).getTitle());
                            } else {
                                //没有免费次数
                                dialogMember();
                            }
                        } else {
                            //收费
                            if (classification.get(position).getIsFlag().equals("0")) {
                                //未购买 弹出购买窗口
                                dialogPay(
                                        classification.get(position).getId(),
                                        classification.get(position).getMoney());
                            } else {//已购买
                                startActivity(new Intent(getContext(), VideoDetailsAc.class)
                                        .putExtra("id", classification.get(position).getId())
                                        .putExtra("title", classification.get(position).getTitle()));
                            }
                        }
                    }
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
            }
        });
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.ll_leaderboard, R.id.ll_recharge, R.id.ll_search, R.id.ll_newest,
            R.id.ll_attention, R.id.ll_choice, R.id.ll_feezone, R.id.ll_auction,
            R.id.iv_home_dialog, R.id.ll_frequency, R.id.ll_recommend, R.id.ll_lottery,
            R.id.ll_preferential})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.ll_preferential:
                //优惠活动
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    getHomeLink(2);
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
                break;
            case R.id.ll_lottery:
                //抽奖
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    getHomeLink(1);
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
                break;
            case R.id.ll_recommend:
                //推荐更多
                startActivity(new Intent(getContext(), RecommendListAc.class));
                break;
            //排行榜
            case R.id.ll_leaderboard:
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    startActivity(new Intent(getContext(), RankingAc.class));
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
                break;
            //充值
            case R.id.ll_recharge:
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    startActivity(new Intent(getContext(), RechargeAc.class));
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
                break;
            //搜索
            case R.id.ll_search:
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    startActivity(new Intent(getContext(), HomeSearchAc.class));
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
                break;
            //最新
            case R.id.ll_newest:
                page2 = 1;
                type1 = "1";
                state = "1";
                getVideoList(page2, type1, state);
                setTextCheck(0);
                break;
            //关注
            case R.id.ll_attention:
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    getFollowVideo(page2, type1, state);
                    setTextCheck(1);
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
                break;
            //精选
            case R.id.ll_choice:
                getGuessLikeVideo();
                setTextCheck(2);
                break;
            //收费专区
            case R.id.ll_feezone:
                page2 = 1;
                type1 = "1";
                state = "2";
                getVideoList(page2, type1, state);
                setTextCheck(3);
                break;
            //拍卖伴侣
            case R.id.ll_auction:
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    startActivity(new Intent(getContext(), AuctionAc.class));
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
                break;
            case R.id.iv_home_dialog:
                //首页加号按钮
                if (null != SPUtil.getObjectFromShare(getContext(),
                        Constants.USERINFO)) {
                    dialog();
                } else {
                    startActivity(new Intent(getContext(), LoginAc.class));
                }
                break;
            case R.id.ll_frequency:
                //频道列表
                startActivity(new Intent(getContext(), FrequencyListAc.class));
                break;
        }
    }

    /**
     * 精选
     */
    private void getGuessLikeVideo() {
        GuessLikeVideoBody guessLikeVideoBody = new GuessLikeVideoBody();
        guessLikeVideoBody.setP("1");
        guessLikeVideoBody.setType1("1");
        ApiUtil.getVideoApi().getGuessLikeVideo(SPUtil.getToken(getContext()),
                guessLikeVideoBody).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<VideoBean>>() {
            @Override
            public void onSuccess(ApiResponse<VideoBean> data) {
                classification.clear();
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    if (null != data.getData().getInfo().get(0).getRecords()) {
                                        for (int i = 0; i < data.getData().getInfo().get(0).getRecords().size(); i++) {
                                            if (data.getData().getInfo().get(0).getRecords().get(i).getCheckStatus().equals("1")) {
                                                classification.add(data.getData().getInfo().get(0).getRecords().get(i));
                                            }
                                        }
                                    }
                                }
                            }
                            classificationAdapter.notifyDataSetChanged();

                            for (int i = 0; i < classification.size(); i++) {
                                int finalI = i;
                                new Thread() {
                                    @Override
                                    public void run() {
                                        super.run();
                                        if (!StringUt.isEmpty(getPlayTime(classification.get(finalI).getVideo()))) {
                                            String time = getFormatedDateTime("mm:ss", Long.valueOf(getPlayTime(classification.get(finalI).getVideo())));
                                            classification.get(finalI).setPeriod(time);
                                            Message msg = new Message();
                                            msg.what = 2;
                                            msg.arg1 = finalI;
                                            handler.sendMessage(msg);
                                        }
                                    }
                                }.start();
                            }
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }
        }));
    }

    /**
     * 首页关注列表
     */
    private void getFollowVideo(int page, String type, String state) {
        ApiUtil.getHomeApi().getFollowVideo(SPUtil.getToken(getContext()),
                String.valueOf(page), type, state
        ).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<VideoBean>>() {
            @Override
            public void onSuccess(ApiResponse<VideoBean> data) {
                classification.clear();
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    if (null != data.getData().getInfo().get(0).getRecords()) {
                                        for (int i = 0; i < data.getData().getInfo().get(0).getRecords().size(); i++) {
                                            if (data.getData().getInfo().get(0).getRecords().get(i).getCheckStatus().equals("1")) {
                                                classification.add(data.getData().getInfo().get(0).getRecords().get(i));
                                            }
                                        }
                                    }
                                }
                            }
                            classificationAdapter.notifyDataSetChanged();

                            for (int i = 0; i < classification.size(); i++) {
                                int finalI = i;
                                new Thread() {
                                    @Override
                                    public void run() {
                                        super.run();
                                        if (!StringUt.isEmpty(getPlayTime(classification.get(finalI).getVideo()))) {
                                            String time = getFormatedDateTime("mm:ss", Long.valueOf(getPlayTime(classification.get(finalI).getVideo())));
                                            classification.get(finalI).setPeriod(time);
                                            Message msg = new Message();
                                            msg.what = 2;
                                            msg.arg1 = finalI;
                                            handler.sendMessage(msg);
                                        }
                                    }
                                }.start();
                            }
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    /**
     * 更多选项
     */
    private void dialog() {
        //创建并显示popWindow
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_home_gd, null);

        CustomPopWindow mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .create()
                .showAsDropDown(iv_home_dialog, 0, 20);

        TextView tv_content1 = contentView.findViewById(R.id.tv_content1);
        TextView tv_content2 = contentView.findViewById(R.id.tv_content2);
        TextView tv_content3 = contentView.findViewById(R.id.tv_content3);
        TextView tv_content4 = contentView.findViewById(R.id.tv_content4);

        tv_content1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), ReleaseVideoAc.class));
                mCustomPopWindow.dissmiss();
            }
        });
        tv_content2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), ShortVideoAc.class));
                mCustomPopWindow.dissmiss();
            }
        });
        tv_content3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), ImageTextAc.class));
                mCustomPopWindow.dissmiss();
            }
        });
        tv_content4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), TextAc.class));
                mCustomPopWindow.dissmiss();
            }
        });

    }


    public void setTextCheck(int position) {
        for (int i = 0; i < textViewList.size(); i++) {
            if (i == position) {
                textViewList.get(position).setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                textViewList.get(position).getPaint().setFakeBoldText(true);
                imageViewList.get(position).setVisibility(View.VISIBLE);
            } else {
                textViewList.get(i).setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                textViewList.get(i).getPaint().setFakeBoldText(false);
                imageViewList.get(i).setVisibility(View.INVISIBLE);
            }
        }
    }

    private String getPlayTime(String mUri) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String duration = "";
        try {
            if (mUri != null) {
                HashMap headers = null;
                if (headers == null) {
                    headers = new HashMap();
                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(mUri, headers);
            } else {
                //mmr.setDataSource(mFD, mOffset, mLength);
            }
            //注意地址 mUri= /storage/emulated/0/youshixiu/rectools/录屏专家190629113518.mp4    本地
            duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);//时长(毫秒)
            String width = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);//宽
            String height = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);//高
        } catch (Exception ex) {
            Log.e("TAG", "MediaMetadataRetriever exception " + ex);
        } finally {
            mmr.release();
        }
        return duration;
    }

    public static String getFormatedDateTime(String pattern, long dateTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
        return sDateFormat.format(new Date(dateTime + 0));
    }


    private boolean isValid(String urlString) {
        try {
            URL url = new URL(urlString);
            return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
        } catch (MalformedURLException e) {

        }
        return false;
    }
}
